//
//  NiubiStyleCell_banner.m
//  danpin
//
//  Created by chuangjia on 16/11/2015.
//  Copyright © 2015 chuangjia. All rights reserved.
//

#import "NiubiStyleCell_banner.h"
#import "TAPageControl.h"
#import "BlackTitleView.h"

#define BANNER_CELL_HEIGHT  135

@interface NiubiStyleCell_banner ()<UIScrollViewDelegate, TAPageControlDelegate>
{
    
}
@property (nonatomic, strong) NSTimer * slideTimer;
@property(nonatomic,strong) UIView * backView;
@property (nonatomic, strong) TAPageControl *bannerPageControl;
@property (strong, nonatomic) UIScrollView *bannerScrollView;

@property (strong, nonatomic) NSMutableArray *bannerViewArray;
@property(nonatomic,assign)int currentPage;

//@property (strong, nonatomic) BlackTitleView *titleBgView;

@end

@implementation NiubiStyleCell_banner

- (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier
{
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self)
    {
        
//        _bannerViewArray = [[NSMutableArray alloc]init];
        self.backgroundColor = [UIColor colorWithRed:0.967 green:0.967 blue:0.967 alpha:1];
        _backView = [[UIView alloc]init];
        _backView.backgroundColor = [UIColor whiteColor];
        _backView.layer.cornerRadius = 3;//(值越大，角就越圆)
        _backView.layer.masksToBounds = YES;
        [self addSubview:_backView];
  
        _bannerScrollView = [[UIScrollView alloc]init];
        _bannerScrollView.backgroundColor = [UIColor clearColor];
        _bannerScrollView.delegate = self;
        _bannerScrollView.pagingEnabled = YES;
        _bannerScrollView.bounces = YES;
        _bannerScrollView.showsHorizontalScrollIndicator = NO;
        _bannerScrollView.showsVerticalScrollIndicator = NO;
        _bannerScrollView.scrollsToTop = NO;
        
        UITapGestureRecognizer *tapGestureRecognizer = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(keyboardHide:)];
        //设置成NO表示当前控件响应后会传播到其他控件上，默认为YES。
        tapGestureRecognizer.cancelsTouchesInView = NO;
        //将触摸事件添加到当前view
        [_bannerScrollView addGestureRecognizer:tapGestureRecognizer];
        tapGestureRecognizer=nil;
        [self addSubview:_bannerScrollView];
        
        //
        _bannerPageControl = [[TAPageControl alloc] initWithFrame:CGRectMake(0, 0, self.bounds.size.width, 20)];
        _bannerPageControl.delegate      = self;
        _bannerPageControl.numberOfPages = 0;
        [self addSubview:_bannerPageControl];
        
    }
    return self;
}

-(void)dealloc
{
    
    
    if(self.slideTimer)
    {
        if (self.slideTimer.isValid) {
            [self.slideTimer invalidate];
        }
        self.slideTimer=nil;
    }
    self.bannerPageControl=nil;
    self.bannerScrollView =nil;
   DLog(@"%s", __PRETTY_FUNCTION__);
}

/// 根据数据模型来显示内容
- (void)showInfo:(id)model key:(id)key indexPath:(NSIndexPath *)indexPath
{
    //todo: 需要测试 一个banner的情况
    //测试cell复用的情况
    
    self.key = key;
    self.indexPath=indexPath;
    NSDictionary *dict =(NSDictionary *)model;
    
    if(dict == nil)
        return;
    
    if([dict isKindOfClass:[NSDictionary class]] == NO)
        return;
    
    self.data =model;
    _backView.frame = CGRectMake(PHOTO_TIME_PADDING, 0, DEVICE_WIDTH - PHOTO_FRAME_WIDTH, BANNER_CELL_HEIGHT );
    
    NSArray *bannerArray = [dict arrayObjectForKey:@"data"];
    if (bannerArray && [bannerArray isKindOfClass:[NSArray class]]) {
        //
        float fHeight = BANNER_CELL_HEIGHT - PHOTO_FRAME_WIDTH;
        float fWidth =  DEVICE_WIDTH - PHOTO_FRAME_WIDTH - PHOTO_FRAME_WIDTH;
        _bannerScrollView.frame = CGRectMake(PHOTO_FRAME_WIDTH, PHOTO_TIME_PADDING, fWidth, fHeight);
        _bannerPageControl.frame = CGRectMake(PHOTO_FRAME_WIDTH, fHeight - PHOTO_FRAME_WIDTH*1.5, 110 , 10);
        int iCount = 0;
        
        for(int idx = 0; idx < [bannerArray count]; idx++)
        {

            NSDictionary* dc = [bannerArray objectAtIndex:idx];
            if(dc == nil || [dc isKindOfClass:[NSDictionary class]] == NO)
            {
                continue;
            }
            
            NSString *imag =[dc stringForKey:@"slide_thumb" withDefaultValue:@""];//[[NSString stringWithFormat:@"%@",[dc objectForKey:@"slide_thumb"]] replaceNullString];
            if (imag.length>0 )
            {
                
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(fWidth * iCount, 0,fWidth, fHeight)];
                imageView.contentMode = UIViewContentModeScaleAspectFill;
                [imageView sd_setImageWithURL:[NSURL URLWithString:imag]];
                [_bannerScrollView addSubview:imageView];
        
                NSString *strTitle =[dc stringForKey:@"banner_title" withDefaultValue:@""];//[[NSString stringWithFormat:@"%@",[dc objectForKey:@"banner_title"]] replaceNullString];
                if(strTitle.length > 0)
                {
                    
                    float fTitleHeight = fHeight / 3;
                    BlackTitleView * titleBgView=[[BlackTitleView alloc] initWithFrame:CGRectMake(0, fHeight - fTitleHeight, fWidth, fTitleHeight)];
                    [imageView addSubview:titleBgView];
                    [titleBgView setTitle:strTitle];
                    titleBgView = nil;
                }
                

                imageView = nil;
                iCount++;
            }
        }
        
        if(iCount > 1)
        {
            _bannerPageControl.hidden = NO;
            
            _bannerPageControl.numberOfPages = iCount;//[_dataArray count];
            if(iCount > 0 && _bannerPageControl.currentPage >= iCount)
            {
                _bannerPageControl.currentPage = iCount-1;
            }
            _bannerScrollView.contentSize = CGSizeMake( _bannerScrollView.frame.size.width *iCount, _bannerScrollView.frame.size.height);
            if (self.slideTimer) {
                [self.slideTimer invalidate];
                self.slideTimer=nil;
            }
            self.slideTimer = [NSTimer scheduledTimerWithTimeInterval:5 target:self selector:@selector(handleSlideTimer:) userInfo:nil repeats:YES];
            
            
        }
        else
        {
            _bannerPageControl.hidden = YES;
        }
        
    }
   
}
/// 返回Cell高度
+ (CGFloat)returnCellHeight:(id)model
{
    return BANNER_CELL_HEIGHT;
}


- (void)handleSlideTimer:(NSTimer *)theTimer
{
 //   return;
    
    if(_bannerPageControl.numberOfPages < 2)
        return;
    
    NSInteger i = _bannerPageControl.currentPage ;//currentPage
    i++;
    if( i  >= _bannerPageControl.numberOfPages )
    {
        i = 0;
    }
    [self TAPageControl:_bannerPageControl didSelectPageAtIndex:i];
}


#pragma mark - ScrollView delegate
// Example of use of delegate for second scroll view to respond to bullet touch event
- (void)TAPageControl:(TAPageControl *)pageControl didSelectPageAtIndex:(NSInteger)index
{
    [self.bannerScrollView scrollRectToVisible:CGRectMake(CGRectGetWidth(self.bannerScrollView.frame) * index, 0, CGRectGetWidth(self.bannerScrollView.frame), CGRectGetHeight(self.bannerScrollView.frame)) animated:YES];
}

// 当开始滚动视图时，执行该方法。一次有效滑动（开始滑动，滑动一小段距离，只要手指不松开，只算一次滑动），只执行一次。
- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    NSLog(@"banner scrollViewWillBeginDragging");
    
    if(self.slideTimer)
    {
        if (self.slideTimer.isValid) {
            [self.slideTimer invalidate];
        }
        self.slideTimer=nil;
    }
    
}


- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(_bannerPageControl.hidden == YES)
        return;
    
    NSInteger pageIndex = scrollView.contentOffset.x / CGRectGetWidth(scrollView.frame);
    _bannerPageControl.currentPage = pageIndex;
}


-(void)keyboardHide:(UITapGestureRecognizer*)tap
{
    NSArray *bannerArray = [self.data arrayObjectForKey:@"data"];
    if (bannerArray && [bannerArray isKindOfClass:[NSArray class]])
    {
        if([bannerArray count] <= 0)
            return;
        
        if (_bannerPageControl.currentPage > [bannerArray count])
        {
            return;
        }
        
        NSDictionary * dc = [bannerArray objectAtIndex:_bannerPageControl.currentPage];
        if(self.actionBlock)
        {
            self.actionBlock(BEventType_banner,self,dc,self.key,self.indexPath);
        }
    }
  
}


@end
